package register;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * 方法注册管理
 * Created by JinMiao
 * 2017/4/20.
 * TODO 优化requestName为数字减少流量
 *
 */
public class RegisterManager
{
    private Map<String, MethodInfo> invokeNameMap = new ConcurrentHashMap<>();

    private Map<Method, MethodInfo> invokeMethodMap = new ConcurrentHashMap<>();

    public void registerService(Class interfaceClass, Object target)
    {
        if(target.getClass().isAssignableFrom(interfaceClass))
        {
            throw new RuntimeException("imp must implement interfaceClass");
        }
        if(!interfaceClass.isInterface())
        {
            throw new RuntimeException("interfaceClass must be interface");
        }
        register(interfaceClass,target);
    }

    private synchronized void register(Class interfaceClass, Object target)
    {
        for(Method method :interfaceClass.getMethods())
        {
            String methodName = method.getName();
            if(methodName.equals("equals")||methodName.equals("hashCode")||methodName.equals("toString"))
                continue;
            if(invokeMethodMap.containsKey(method))
                continue;
            MethodInfo methodInfo = new MethodInfo(method,target);
            this.invokeNameMap.put(methodInfo.getRequestName(), methodInfo);
            this.invokeMethodMap.put(method,methodInfo);
        }
    }


    public void register(Class interfaceClass)
    {
        register(interfaceClass,null);
    }

    public MethodInfo getMethod(Method method)
    {
        return invokeMethodMap.get(method);
    }

    public MethodInfo getMethod(String requestName)
    {
        return invokeNameMap.get(requestName);
    }


}
